package org.wmq.organizationmanagement.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.wmq.organizationmanagement.mapper.OrganizationMapper;
import org.wmq.organizationmanagement.mapper.OrganizationMasterMapper;
import org.wmq.organizationmanagement.model.po.Organization;
import org.wmq.organizationmanagement.model.vo.OrganizationVO;
import org.wmq.organizationmanagement.service.OrganizationMasterService;
import org.wmq.organizationmanagement.service.OrganizationMemberService;
import org.wmq.organizationmanagement.service.OrganizationService;

import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class OrganizationServiceImpl extends ServiceImpl<OrganizationMapper, Organization> implements OrganizationService {
    private final OrganizationMemberService organizationMemberService;
    private final OrganizationMasterService organizationMasterService;
    @Override
    public List<OrganizationVO> getListByName(String name) {
        List<Organization> organizationList = this.lambdaQuery().like(Organization::getName, name)
                .list();
        if (organizationList == null){
            return null;
        }
        return organizationList.stream().map(organization -> {
            OrganizationVO organizationVO = new OrganizationVO();
            BeanUtils.copyProperties(organization, organizationVO);
            return organizationVO;
        }).toList();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOrganizationById(Long id) {
        boolean removeSuccess = this.removeById(id);
        if (!removeSuccess){
            log.error("删除组织失败");
            throw new RuntimeException("删除组织失败");
        }
        this.organizationMemberService.deleteByOrganizationID(id);
        this.organizationMasterService.removeByOrganizationId(id);

        log.info("删除组织成功");
    }
}
